import MyTable from '@/components/MyTable';
import { edit, editKeys, findByPageList } from '@/services/poster';
import { getResult } from '@/services/sys/attribute';
import { BetaSchemaForm, ProFormInstance } from '@ant-design/pro-form';
import { ProFormColumnsType } from '@ant-design/pro-form/es/components/SchemaForm/typing';
import { message, Modal, Transfer } from 'antd';
import { TransferDirection } from 'antd/es/transfer';
import React, { useRef, useState } from 'react';
interface RecordType {
  key: string;
  title: string;
  description: string;
}

var result = await getResult('systemposterkeyvalue', 1);
const mockData: RecordType[] = result.map((_, i) => ({
  key: _?.value,
  title: _?.label,
  description: _?.label,
}));
const initialTargetKeys = mockData
  .filter((item) => Number(item.key) > 10)
  .map((item) => item.key);
export const Index: React.FC = () => {
  const [targetKeys, setTargetKeys] = useState(initialTargetKeys);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const formRef = useRef<ProFormInstance<API.Agent>>();
  const [editDialg, setEditDialg] = useState(false);
  const [agents, setAgents] = useState<API.Agent>({});
  const [id, setId] = useState<Number>(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  function hideEditDialg() {
    setAgents({ ...agents, id: 0 });
    formRef.current?.resetFields();
    formRef?.current?.setFieldsValue({ id: 0 });
    setEditDialg(false);
  }

  function openEditDialg() {
    setAgents({ id: 0 });
    formRef.current?.resetFields();
    formRef?.current?.setFieldsValue({
      name: '',
      id: 0,
      nameUg: '',
      price: 0,
      level: 0,
    });
    setEditDialg(true);
  }

  function editDialogInfo(row: API.Agent, index: number) {
    setAgents(row);
    console.log('editDialogInfo', row);
    formRef?.current?.setFieldsValue(row);
    //  formRef?.current?.setFieldsValue ( {id: row.id}  );
    console.log('editDialogInfo', formRef?.current?.getFieldsValue());
    setEditDialg(true);
  }

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    console.log('Cancelling', targetKeys, id);
    if (targetKeys.length > 0) {
      let s = targetKeys.join(',');
      editKeys({ attrs: s, id: id }).then((res) => {
        let success = res.success;
        if (success) {
          message.success('操作成功');
          //  fetchByPageList ()
          setTargetKeys([]);
        } else {
          message.error('操作失败');
        }
      });
      setIsModalOpen(false);
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onChange = (
    nextTargetKeys: string[],
    direction: TransferDirection,
    moveKeys: string[],
  ) => {
    //   console.log('targetKeys:', nextTargetKeys);
    //  console.log('direction:', direction);
    //  console.log('moveKeys:', moveKeys);
    setTargetKeys(nextTargetKeys);
  };

  const onSelectChange = (
    sourceSelectedKeys: string[],
    targetSelectedKeys: string[],
  ) => {
    //  console.log('sourceSelectedKeys:', sourceSelectedKeys);
    //   console.log('targetSelectedKeys:', targetSelectedKeys);
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };
  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },

    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 'md',
    },
    {
      title: '维语名称',
      dataIndex: 'nameUg',
      key: 'nameUg',
      width: 'md',
    },
    {
      title: 'Attr',
      dataIndex: 'attr',
      key: 'attr',
      width: 'md',
    },
    {
      title: '操作',
      width: '164px',
      key: 'option',
      valueType: 'option',
      render: (_: any, row: API.Agent, index: number, action: any) => [
        <a
          key="link"
          onClick={(a) => {
            console.log(row);
            setAgents(row);
            editDialogInfo(row, index);
          }}
        >
          编辑
        </a>,
        <a
          key="link"
          onClick={(a) => {
            // console.log ( row );
            let attr = row?.attr;
            setTargetKeys(attr?.split(','));
            setId(row?.id);
            showModal();
          }}
        >
          数据编辑
        </a>,
      ],
    },
  ];
  const columnDialog: ProFormColumnsType<API.Agent>[] = [
    {
      title: '基本信息',
      valueType: 'group',
      columns: [
        {
          title: 'id',
          dataIndex: 'id',
          key: 'id',

          formItemProps: {
            hidden: true,
          },
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          width: 'md',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
        {
          title: '维语名称',
          dataIndex: 'nameUg',
          key: 'nameUg',
          width: 'md',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
        {
          title: '关键字',
          dataIndex: 'type',
          key: 'type',
          width: 'md',
          valueType: 'digit',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
      ],
    },
  ];
  const [columnDialogs, setColumnDialogs] = useState(columnDialog);
  return (
    <>
      <Modal
        title="数据选择"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Transfer
          dataSource={mockData}
          titles={['源', '选择']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}
          render={(item) => item.title}
        />
      </Modal>
      <BetaSchemaForm<API.Agent>
        formRef={formRef}
        initialValues={agents}
        onCancel={() => setEditDialg(false)}
        onVisibleChange={setEditDialg}
        title="产品分类"
        visible={editDialg}
        layoutType="ModalForm"
        columns={columnDialogs}
        // @ts-ignore
        onFinish={async (values) => {
          // @ts-ignore
          //   values.id=category.id;
          //setCategory({...category,...values})

          //  values = Object.assign ( category, values )
          console.log(agents, values);
          return new Promise<Boolean>((resolve, reject) => {
            // @ts-ignore
            edit(values)
              .then(() => {
                message.success('操作成功');
                setEditDialg(false);
                // refresh ();
                resolve(true);
              })
              .catch(() => {
                message.success('操作失败');
                reject(false);
              });
          });
        }}
      />
      <MyTable request={findByPageList} columns={columns} />
    </>
  );
};
export default Index;
